//
//  JPview.m
//  Jpod
//
//  Created by zenox on 2022/4/6.
//

#import "JPview.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>



@interface JPview ()<AVAssetResourceLoaderDelegate>



// 播放器的Layer
@property (strong, nonatomic) AVPlayerLayer *playerLayer;
/* 播放器 */
@property (nonatomic, strong) AVPlayer *player;

@property (nonatomic, strong) UIButton *playButton;

@property (nonatomic, strong) AVPlayerItem *currentItem;

@end


@implementation JPview
- (void)sssss{
    
    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/


- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor grayColor];
//        [self stepUI];
        [self uuuuu];
    }
    return self;
}


- (void)uuuuu{
    
  
    
}
- (void)stepUI{
    
    //创建AVPlayerLayer
    self.playerLayer = [[AVPlayerLayer alloc] init];
    //frame
    self.playerLayer.frame = self.bounds;
    
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;

    //去除黑边
    //使playerLayer光栅化(即位图化)，关闭了图层的blending(混合)。
    self.playerLayer.shouldRasterize = YES;
    //显式指定光栅化的范围，这样能保证视频的显示质量，不然容易出现视频质量显示不佳。
    self.playerLayer.rasterizationScale = [UIScreen mainScreen].scale;

    //在view的layer上添加layer
    [self.layer addSublayer:self.playerLayer];
    
    //方式二
    //类方法通过URl地址创建要播放的对象 可以是本地内容也可以是在线内容
//    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.url]];

    //切换视频资源
//    [self.player replaceCurrentItemWithPlayerItem:item];

    [self.playerLayer setPlayer:self.player];
    //方式一
    //通过设备相册里面的内容 创建一个要播放的对象
//    AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL: [NSURL URLWithString:@"file:///var/mobile/Containers/Data/Application/844D2D16-AEAB-4646-B12E-157A10B041B9/Documents/output-2022-04-06-21:12:23.mp4"] options: nil];
    AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL: [NSURL URLWithString:@"file:///var/mobile/Media/DCIM/100APPLE/IMG_0023.MOV"] options: nil];

    [[urlAsset resourceLoader] setDelegate: self queue: dispatch_get_main_queue()];
    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:urlAsset];
    self.currentItem = item;
    
    [self.player replaceCurrentItemWithPlayerItem:self.currentItem];
    
    [self.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
   
    [self addSubview:self.playButton];


    //通过KVO来观察status属性的变化，来获得播放之前的错误信息
    [_player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
                     
    self.player.automaticallyWaitsToMinimizeStalling = NO;
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status = [change[NSKeyValueChangeNewKey] intValue];
        switch (status) {
            case AVPlayerStatusFailed:
            {
                NSLog(@"url有误");
            }
                break;
            case AVPlayerStatusReadyToPlay:
            {
                NSLog(@"准备好播放了");
            
            }
                break;
            case AVPlayerStatusUnknown:
            {
                NSLog(@"视频资源出现未知错误");
            }
                break;
            default:
                break;
        }
    }
}

- (UIButton *)playButton{
    if (_playButton == nil) {
        self.playButton = [UIButton buttonWithType:UIButtonTypeSystem];
        self.playButton.frame = CGRectMake(0, 0, 50, 50);
        self.playButton.center = self.center;
//                self.playButton.backgroundColor = [UIColor redColor];
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
//        [self.playButton se]
        [self.playButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _playButton;
}

- (void)btnClick:(id)sender{
    
    [self.player play];
}

#pragma mark - 设置播放的视频
- (void)setUrlString:(NSString *)urlString
{
    return;
    _urlString = urlString;
   
    NSURL *url = [NSURL URLWithString:urlString];
    if (self.player.currentItem) {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    }
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
    self.currentItem = item;
    
    [self.player replaceCurrentItemWithPlayerItem:self.currentItem];
    
    [self.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    // 添加视频播放结束通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_currentItem];
    
}
- (void)moviePlayDidEnd:(NSNotification *)notification {
    __weak typeof(self) weakSelf = self;
    [self.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
//        [weakSelf.progressSlider setValue:0.0 animated:YES];
//        weakSelf.playOrPauseBtn.selected = NO;
    }];
}
@end
